package com.example.springvue.common.handler;

//import com.example.demos.common.PassToken;
//import com.example.demos.model.AdminUser;
//import com.example.demos.service.AdminUserService;
//import com.example.demos.service.UserTokenService;

import com.example.springvue.common.annotation.PassToken;
import com.example.springvue.common.jwt.JwtUtils;
import com.example.springvue.model.AdminUser;
import com.example.springvue.model.AdminUserHeader;
import com.example.springvue.service.AdminUserService;
import org.assertj.core.util.Arrays;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;


/**
 * JWT拦截器
 */
public class JwtAuthenticationInterceptor implements HandlerInterceptor {
    @Autowired
    AdminUserService adminUserService;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        // 从请求头中取出 token  这里需要和前端约定好把jwt放到请求头一个叫token的地方
        String token = httpServletRequest.getHeader("token");
        // 如果不是映射到方法直接通过
        String url = httpServletRequest.getServletPath();
        List<Object> split= Arrays.asList(url.split("/"));
        System.out.println(split);

        if (split.get(1).equals("images")||split.get(1).equals("error")){
            return true;
        }
        System.out.println(url);
        if (!(object instanceof HandlerMethod)) {

            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();
        //检查是否有passtoken注释，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }
        System.out.println(method.isAnnotationPresent(PassToken.class));
        //默认全部检查
        // 执行认证
        if (token == null || token == "") {
            //这里其实是登录失效,没token了   这个错误也是我自定义的，读者需要自己修改
            throw new TokenNotExistException("未登录");
        }
        // 获取 token 中的 user Name
        String userInfo = JwtUtils.getAudience(token);
        Integer userId = JwtUtils.getClaimByName(token, "userId").asInt();
        // 验证 token
        JwtUtils.verifyToken(token, userId);
        //token验证通过后获取用户信息
        //获取载荷内容
        String type = JwtUtils.getClaimByName(token, "type").asString(); //登录类型 后台登录和其他登录
        if (type.equals("admin")) { //后台用户登录
            //获取登录用户信息
            AdminUser adminUser = adminUserService.getAdminUserInfoId(userId);
            //保存登录用户信息
            AdminUserHeaderHodler.set(adminUser);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest,
                           HttpServletResponse httpServletResponse,
                           Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest,
                                HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {
        AdminUserHeaderHodler.remove();//释放ThreadLocal
    }
}
